#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : Lee
# @File    : dhy_resource_collection_view.py
# @Time    : 2024/1/24 15:27
import json
import numpy as np
import matplotlib.pyplot as plt


def format_matplotlib_view_data_from_files_path(files_path):
    x_label_data = list()
    planning_list = list()
    control_list = list()
    pose_list = list()
    client_list = list()

    for file_path in files_path:
        with open(file_path, 'r')as f_obj:
            for line_data in f_obj.readlines():
                _line_json = json.loads(line_data.strip())
                if type(_line_json) != dict:
                    continue
                x_label_data.append(_line_json["timestamp"])
                planning_list.append(_line_json["planning"])
                control_list.append(_line_json["control"])
                pose_list.append(_line_json["localization_component"])
                client_list.append(_line_json["Client"])

    _planning_matrix = np.array(planning_list)
    _control_matrix = np.array(control_list)
    _pose_matrix = np.array(pose_list)
    _client_matrix = np.array(client_list)

    cpu_y_label = [{
        "label": "planning",
        "color": "r-",
        "value": _planning_matrix[:, 2]
    }, {
        "label": "control",
        "color": "y-",
        "value": _control_matrix[:, 2]
    }, {
        "label": "pose",
        "color": "g-",
        "value": _pose_matrix[:, 2]
    }, {
        "label": "client",
        "color": "b-",
        "value": _client_matrix[:, 2]
    }]

    memory_y_label = [{
        "label": "planning",
        "color": "r-",
        "value": _planning_matrix[:, 1]
    }, {
        "label": "control",
        "color": "y-",
        "value": _control_matrix[:, 1]
    }, {
        "label": "pose",
        "color": "g-",
        "value": _pose_matrix[:, 1]
    }, {
        "label": "client",
        "color": "b-",
        "value": _client_matrix[:, 1]
    }]
    return x_label_data, cpu_y_label, memory_y_label


def show_dhy_resource_collection_view(files_path):
    x_label_data, cpu_y_label, memory_y_label = format_matplotlib_view_data_from_files_path(files_path)
    # plt.figure(figsize=(16, 10))
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6))
    ax1.set_title("cpu(%)")
    ax2.set_title("memory(%)")
    for item in cpu_y_label:
        ax1.plot(x_label_data, item["value"], item["color"], label=item["label"])
    for item in memory_y_label:
        ax2.plot(x_label_data, item["value"], item["color"], label=item["label"])
    ax1.grid()
    ax1.legend(loc="upper left")
    ax2.grid()
    ax2.legend(loc="upper left")
    plt.show()
